//app.js
import { apiUrl } from './config';
App({
  onLaunch: () => {
    wx.showLoading({
      title: '加载中',
    })
    wx.checkSession({
      success: (res) => {
        console.log(res);
        try {

        } catch (e) {
          console.log(e);
        }
      },
      fail: function () {
        //登录态过期
        try {
          wx.clearStorageSync();
        } catch (e) {
          console.log(e);
        }
      }
    })
  },
  checkToken() { //检查缓存中是否有token， 存入globalData
    try {
      const value = wx.getStorageSync('token');
      if (value) {
        this.globalData.token = value;
        return value;
      }
      return null;
    } catch (e) {
      console.log(e);
    }
  },
  getUserInfo: function (cb) {
    let token = this.checkToken();
    wx.login({
      success: (result) => {
        console.log(result)
        if (result.code) {
          wx.getUserInfo({
            success: (res) => {
              this.login({
                code: result.code,
                nickname: res.userInfo.nickName,
                avatar: res.userInfo.avatarUrl
              }, () => {
                typeof cb == "function" && cb();
              });
              this.globalData.userInfo = res.userInfo;
            },
            fail: function (err) {
              console.log(err);
            }
          })
        } else {
          console.log(result)
        }
      },
      fail: (err) => {
        console.log(err);
      }
    })
  },
  login(data, cb) {
    wx.request({
      url: apiUrl + '/login',
      method: 'POST',
      data,
      success: (res) => {
        console.log(res);
        if (res.data.code == 1) {
          const token = !!res.data.token ? 'Bearer ' + res.data.token : '';
          wx.setStorageSync('token', token);
          this.globalData.token = token;
          typeof cb == "function" && cb();
          console.log(token);
        } else {
          console.log(res.data.msg);
        }
      },
      fail: (err) => {
        console.log(1);
        console.log(err);
      }
    })
  },
  globalData: {
    userInfo: null,
    token: null,
    feeds: []
  }
})
